package com.lightjet.macross.base.awf.service.impl;

import com.lightjet.macross.base.awf.domain.BizAgent;
import com.lightjet.macross.base.awf.repository.BizAgentRepository;
import com.lightjet.macross.base.awf.service.BizAgentService;
import com.lightjet.macross.base.awf.service.ProcessService;
import com.lightjet.macross.common.core.BaseServiceImpl;
import com.lightjet.macross.common.dto.ResultDTO;
import lombok.extern.java.Log;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : lijia
 * @version : 1.0 2019-04-03 09:26
 * description : 流程代理服务层接口实现
 */
@Service
@Log
public class BizAgentServiceImpl extends BaseServiceImpl<BizAgent,Integer> implements BizAgentService {

    @Resource
    private ProcessService processService;
    /**
     * Description 刷新当前代理表中已经过期的授权
     *
     * @return com.lwl.jmf.core.dto.ResultDTO
     * CreateTime 2019/4/3 9:25
     * @author lijia
     * @Param []
     **/
    @Override
    public ResultDTO RefreshExpired() {
        try
        {
            ((BizAgentRepository)baseRepository).refreshExpired();
            return ResultDTO.CreateOKResult();
        }
        catch (Exception e)
        {
            return ResultDTO.CreateErrorResult("刷新过期授权失败："+e.getMessage());
        }
    }

    /**
     * Description 根据被代理人ID获取已经授权的代理信息
     *
     * @param principalid
     * @return java.util.List<com.lwl.jmf.activiti.domain.BizAgent>
     * CreateTime 2019/4/3 9:40
     * @author lijia
     * @Param [principalid]
     */
    @Override
    public List<BizAgent> GetAgentsByPrincipalId(String principalid,byte enable) {
        BizAgentRepository bizAgentRepository =((BizAgentRepository)baseRepository);
        return principalid.equals("*")? bizAgentRepository.findByEnable(enable) : bizAgentRepository.findByPrincipalIdAndEnable(principalid,enable);
    }

    /**
     * Description 批量撤销授权
     *
     * @param ids
     * @return com.lwl.jmf.core.dto.ResultDTO
     * CreateTime 2019/4/5 10:50
     * @author lijia
     * @Param [ids]
     */

    @Override
    public ResultDTO BatchExpire(List<Integer> ids) {
        try{
            ((BizAgentRepository)baseRepository).batchExpire(ids);
            return ResultDTO.CreateOKResult();
        }
        catch (Exception e)
        {
            return ResultDTO.CreateErrorResult("批量撤销失败："+e.getMessage());
        }

    }

    /**
     * description:批量处理授权代理操作
     *
     * @param agents
     * @param trans
     */
    @Override
    @Transactional
    public ResultDTO GrantAgent(List<BizAgent> agents, boolean trans) {
        StringBuilder sb = new StringBuilder();
        if(RefreshExpired().isSuccess()) {

            for(BizAgent agent : agents) {
                List<BizAgent> grantedlist = GetAgentsByPrincipalId(agent.getPrincipalId(), (byte) 1);
                if(agents.stream().filter(x-> x.getGrantedprockey().equals("*")).count()>=0&& grantedlist.size()>0) //本次授权* 全部 但存在已生效的授权 则覆盖掉
                {
                    for(BizAgent old : grantedlist)
                    {
                        old.setMemo("授权被覆盖");
                        old.setEnable((byte) 0);
                        UpdateAndFlush(old);
                    }
                }
                if (grantedlist.stream().filter(e -> e.getGrantedprockey().equals("*") || e.getGrantedprockey().equals(agent.getGrantedprockey())).count() == 0) {
                    if (CreateAndFlush(agent) == null) {
                        sb.append("流程【"+agent.getGrantedprocname()+"】授权失败");
                    }
                } else {
                    sb.append("流程【" + agent.getGrantedprocname() + "】授权已存在,如需修改请先撤回");
                }
            }

        }
        else
        {
            sb.append("刷新过期授权失败");
        }
        if(sb.length()==0 && trans) //需要转交当前在途流程任务
        {
            for(BizAgent agent : agents){
                List<Task> taskList = processService.GetAllMyTask(agent.getPrincipalId());
                for(Task task : taskList)
                {
                    try {
                        log.info("正在在进行任务【"+task.getAssignee()+"】途流程转办（从【"+agent.getPrincipalId()+"】到【"+agent.getAgentId()+"】）");
                        processService.ChangeAssinee(task.getId(),agent.getAgentId());
                    }
                    catch (Exception e)
                    {
                        sb.append("在途流程任务【"+task.getAssignee()+"】转办失败（从【"+agent.getPrincipalId()+"】到【"+agent.getAgentId()+"】）："+e.getMessage());
                    }
                }
            }
        }
        if(sb.length()==0)
        {
            return ResultDTO.CreateOKResult("授权操作成功");
        }
        else
        {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultDTO.CreateErrorResult(sb.toString());
        }
    }


}
